package com.example.lastwork2.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.lastwork2.R;
import com.example.lastwork2.fragments.detail.OrderDetailActivity;
import com.example.lastwork2.model.Order;
import com.example.lastwork2.model.Shop;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OrderShopAdapter extends BaseAdapter {

    //获取上下文环境
    private Context context;
    //获取item布局
    private int layoutId;
    //数据源
    private List<Shop> shops;

    //布局控件
    private ImageView shopIcon;
    private TextView shopName;
    private TextView shopBrief;
    private TextView shopPrice;
    private TextView shopNum;







    public OrderShopAdapter(){

    }

    public OrderShopAdapter(Context context, int layoutId, List<Shop> shops) {
        this.context = context;
        this.layoutId = layoutId;
        this.shops = shops;
    }

    @Override
    public int getCount() {
        return shops.size();
    }

    @Override
    public Object getItem(int position) {
        return shops.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        //获取布局文件对象
        View view = LayoutInflater.from(context).inflate(layoutId,null);
        //1.获取布局文件控件对象
        shopIcon = view.findViewById(R.id.shop_icon);
        shopName = view.findViewById(R.id.shop_name);
        shopBrief = view.findViewById(R.id.shop_brief);
        shopPrice = view.findViewById(R.id.shop_price);
        shopNum = view.findViewById(R.id.shop_num);
        //2.获取数据源中当前位置的对象

        Shop shop = shops.get(position);

        //3.把数据显示到对应控件中去
        Glide.with(context)
                .load(shop.getIcon())
                .into(shopIcon);

        shopName.setText(shop.getShopName());
        shopBrief.setText(shop.getShopBrief());
        String price = String.valueOf(shop.getPrice());
        shopPrice.setText("￥"+price);
        //放入商品数量时要在shops里面查找一下有几个当前商品
        Map<Shop,Integer> map = new HashMap<>();
        for(Shop shop1 : shops){
            Integer i = 1;
            if(map.get(shop1)!=null){
                i = map.get(shop1) + 1;
            }
            map.put(shop1,i);
        }
        int count = map.get(shop);
        String count1 = String.valueOf(count);
        shopNum.setText(count1);
        //总价格
        Double sum = 0.0;
        for(Shop shop1 : shops){
            sum = sum + shop1.getPrice();
        }
        String sump = String.valueOf(sum);
        OrderDetailActivity.sumPrice.setText(sump);






        return view;
    }
}
